from django.contrib.auth import logout
from django.contrib.auth.hashers import check_password
from django.shortcuts import render

# Create your views here.
from rest_framework.pagination import PageNumberPagination

from rest_framework_simplejwt.views import TokenObtainPairView

from utils.pagination import MyPagePagination
from utils.permissions import RegisterPermission
from .serializer import *
from .models import *
from rest_framework.viewsets import ModelViewSet
from rest_framework import permissions
from rest_framework.response import Response
from utils.errormsg import erromsg
from utils.status import CODE_0, CODE_1


class UserView(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializers
    pagination_class = MyPagePagination

    # permission_classes = [RegisterPermission]

    def user_register(self, request, *args, **kwargs):

        data = request.data
        serializer = self.serializer_class(data=data)
        try:
            User.objects.get(username=data["username"])
            return Response({**CODE_1, "msg": "用户已存在"})
        except Exception:
            if not serializer.is_valid():
                return Response({**CODE_1, "msg": erromsg(serializer)})
            instance = serializer.save()
            instance.set_password(data["password"])
            instance.save()
        return Response({**CODE_0})

    def userlist(self, request, *args, **kwargs):
        query_set = self.queryset
        param = request.query_params
        if param.get("username"):
            query_set = query_set.filter(username__contains=param.get("username"))
        if param.get("usertype"):
            query_set = query_set.filter(usertype=param.get("usertype"))
        ser = self.serializer_class(query_set, many=True)
        if not ser.data:
            return Response({**CODE_1})
        return Response({**CODE_0, "data": ser.data})

    # def list(self, request, *args, **kwargs):
    #     query_set = self.queryset
    #     param = request.query_params
    #     if param.get("username"):
    #         query_set = query_set.filter(username__contains=param.get("username"))
    #     if param.get("usertype"):
    #         query_set = query_set.filter(usertype=param.get("usertype"))
    #     ser = self.serializer_class(query_set, many=True)
    #     if not ser.data:
    #         return Response({**CODE_1})
    #     return Response({**CODE_0, "data": ser.data})
    def userdetail(self, request, pk):
        query_set = self.queryset
        query_set = query_set.filter(id=pk)

        if not query_set:
            return Response({**CODE_1, "msg": "用户不存在"})
        ser = self.serializer_class(query_set, many=True)
        return Response({**CODE_0, "data": ser.data})

    @staticmethod
    def userlogout(request):
        # TODO: 是否保存在redis并清空
        return Response({**CODE_0})


class GetLoginTokenView(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = GetLoginTokenSerializers

    def login(self, request):
        """
        :param request:
        :return:
        """
        data = request.data

        if not data.get("username"):
            return Response({**CODE_1, "msg": "username必填"})
        if not data.get("password"):
            return Response({**CODE_1, "msg": "password必填"})
        user = User.objects.filter(username=data.get("username")).first()
        try:
            if check_password(data.get("password"), user.password):
                pass
            else:
                return Response({**CODE_1, "msg": "用户名或者密码错误"})
        except AttributeError:
            return Response({**CODE_1, "msg": "用户名或者密码错误"})

        ser = self.serializer_class(data=request.data, )
        if not ser.is_valid():
            return Response({**CODE_1, "msg": erromsg(ser)})
        token = ser.validate(request.data)
        token.pop("refresh")
        return Response({**CODE_0, "data": token})
